﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace MyWords.MyAudio
{
    public class AudioRecorder
    {
        #region "Private properties, events and fields"

        static Istrib.Sound.SoundCapture m_Recorder;
        static MemoryStream m_Stream;

        #endregion

        #region "Public properties, events and fields"

        public static Istrib.Sound.SoundCaptureDevice m_Device = Istrib.Sound.SoundCaptureDevice.Default;
        public static Istrib.Sound.Formats.PcmSoundFormat m_Format = Istrib.Sound.Formats.PcmSoundFormat.Pcm22kHz8bitMono;

        #endregion

        #region "Constructors"

        #endregion

        #region "Public methods"

        public static void StartRecord()
        {
            if (m_Stream == null || m_Recorder == null)
            {
                m_Stream = new MemoryStream();
                m_Recorder = new Istrib.Sound.SoundCapture(m_Format, m_Stream, true);
                m_Recorder.CaptureDevice = m_Device;
            }
            m_Recorder.Start();
        }

        public static void StopRecord()
        {
            if (m_Recorder != null)
            {
                m_Recorder.Stop();
            }
        }

        public static void Rewind()
        {
            if (m_Recorder != null)
            {
                m_Recorder.Stop();
                m_Recorder.Dispose();
                m_Recorder = null;
            }

            if (m_Stream != null)
            {
                m_Stream.Close();
                m_Stream.Dispose();
            }
        }

        public static int SaveToStream(Stream aStream)
        {
            if (m_Stream != null)
            {
                byte[] m_Buffer = m_Stream.GetBuffer();
                int m_Length = (int)m_Stream.Length;
                aStream.Write(m_Buffer, 0, m_Length);
                return m_Length;
            }
            
            return 0;
        }

        internal static byte[] SaveToBytes()
        {
            if (m_Stream != null)
            {
                byte[] m_Buffer = m_Stream.GetBuffer();
                int m_Length = (int)m_Stream.Length;
                byte[] bytes = new byte[m_Length];
                Buffer.BlockCopy(m_Buffer, 0, bytes, 0, m_Length);
                return bytes;
            }
            return null;
        }

        #endregion


    }
}
